package com.yinhai.message.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.yinhai.core.app.ta3.web.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

/**
 * Created by renxin on 2019/4/2 0002.
 */
@Controller
@RequestMapping("testSendMessage")
public class TestSendMessageController extends BaseController {
    //接入系统编号
    private static final String access_key = "portal_test";
    //服务编号
    private static final String format = "json";
    //版本号
    private static final String version = "1.0";


    @RequestMapping("toTest.do")
    public String execute() throws Exception{
        return "test";
    }

    @RequestMapping("testSms.do")
    public String testSms() throws Exception{
        Map<String,Object> sendUser = new HashMap<>();
        sendUser.put("appId","portal_test");
        sendUser.put("userId","developer");
        sendUser.put("name","管理员");

        List<Map<String,Object>> receiveUserList = new ArrayList<>();
        Map<String,Object> receiveUser = new HashMap<>();
        receiveUser.put("appId","portal_test");
        receiveUser.put("userId","1");
        receiveUser.put("name","renxin");
        receiveUser.put("sms","15882449573");
        receiveUserList.add(receiveUser);

        Map<String,Object> msg = new HashMap<>();
        msg.put("title","消息测试");
        msg.put("content","收到了吧");
        msg.put("text","你好");
        msg.put("selfType","4");
        msg.put("toAllUser",false);

        String type = "0";//系统内部推送
        String type1 = "1";//email
        String type2 = "5"; //IM
        String type3 = "4";//app
        String type4 = "2";//微信
        String type5 = "3";//短信
        List<String> types = new ArrayList<>();
		types.add(type5);
        msg.put("messageTypes",types);
        Map<String,Object> message = new HashMap<>();
        message.put("user",sendUser);
        message.put("userlist",receiveUserList);
        message.put("message",msg);
        message.put("wechat",null);
        long start = System.currentTimeMillis();
        executeHttp(message);
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return JSON;
    }

    @RequestMapping("testEmail.do")
    public String testEmail() throws Exception{
        Map<String,Object> sendUser = new HashMap<>();
        sendUser.put("appId","portal_test");
        sendUser.put("userId","developer");
        sendUser.put("name","管理员");

        List<Map<String,Object>> receiveUserList = new ArrayList<>();
        Map<String,Object> receiveUser = new HashMap<>();
        receiveUser.put("appId","portal_test");
        receiveUser.put("userId","1");
        receiveUser.put("name","renxin");
        receiveUser.put("email","972618554@qq.com");
        receiveUserList.add(receiveUser);

        Map<String,Object> msg = new HashMap<>();
        msg.put("title","消息测试");
        msg.put("content","收到了吧");
        msg.put("text","你好");
        msg.put("selfType","4");
        msg.put("toAllUser",false);

        String type = "0";//系统内部推送
        String type1 = "1";//email
        String type2 = "5"; //IM
        String type3 = "4";//app
        String type4 = "2";//微信
        String type5 = "3";//短信
        List<String> types = new ArrayList<>();
        types.add(type1);
        msg.put("messageTypes",types);
        Map<String,Object> message = new HashMap<>();
        message.put("user",sendUser);
        message.put("userlist",receiveUserList);
        message.put("message",msg);
        message.put("wechat",null);
        long start = System.currentTimeMillis();
        executeHttp(message);
//        yhbcp_httpRequset(message);
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return JSON;
    }

    @RequestMapping("testWechat.do")
    public String testWechat() throws Exception{
        Map<String,Object> sendUser = new HashMap<>();
        sendUser.put("appId","portal_test");
        sendUser.put("userId","developer");
        sendUser.put("name","管理员");

        List<Map<String,Object>> receiveUserList = new ArrayList<>();
        Map<String,Object> receiveUser = new HashMap<>();
        receiveUser.put("appId","portal_test");
        receiveUser.put("userId","1");
        receiveUser.put("name","renxin");
        receiveUser.put("wechat","oHRlo6BBXjByigwpxEOr_Iffg47M");
        receiveUserList.add(receiveUser);

        Map<String,Object> msg = new HashMap<>();
        msg.put("title","消息测试");
        msg.put("content","收到了吧");
        msg.put("text","你好");
        msg.put("selfType","4");
        msg.put("toAllUser",false);

        String type = "0";//系统内部推送
        String type1 = "1";//email
        String type2 = "5"; //IM
        String type3 = "4";//app
        String type4 = "2";//微信
        String type5 = "3";//短信
        List<String> types = new ArrayList<>();
//        Map<String,Object> wechat = new HashMap<>();
//        wechat.put("secret","c7ac01bf0609b11b6b142fbebe46d223");
//        wechat.put("appid","wxd10942fa7da7743b");
//        wechat.put("accessToken","");
        types.add(type4);
        msg.put("messageTypes",types);
        Map<String,Object> message = new HashMap<>();
        message.put("user",sendUser);
        message.put("userlist",receiveUserList);
        message.put("message",msg);
        message.put("wechat",null);
        long start = System.currentTimeMillis();
        executeHttp(message);
//        yhbcp_httpRequset(message);
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return JSON;
    }

    @RequestMapping("testApp.do")
    public String testApp() throws Exception{
        Map<String,Object> sendUser = new HashMap<>();
        sendUser.put("appId","portal_test");
        sendUser.put("userId","developer");
        sendUser.put("name","管理员");

        List<Map<String,Object>> receiveUserList = new ArrayList<>();
        Map<String,Object> receiveUser = new HashMap<>();
        receiveUser.put("appId","portal_test");
        receiveUser.put("userId","1");
        receiveUser.put("name","renxin");
		receiveUser.put("registrationId","140fe1da9ef461a9882");
        receiveUserList.add(receiveUser);

        Map<String,Object> msg = new HashMap<>();
        msg.put("title","消息测试");
        msg.put("content","收到了吧");
        msg.put("text","你好");
        msg.put("selfType","4");
        msg.put("toAllUser",true);

        String type = "0";//系统内部推送
        String type1 = "1";//email
        String type2 = "5"; //IM
        String type3 = "4";//app
        String type4 = "2";//微信
        String type5 = "3";//短信
        List<String> types = new ArrayList<>();
        types.add(type3);
        msg.put("messageTypes",types);
        Map<String,Object> message = new HashMap<>();
        message.put("user",sendUser);
        message.put("userlist",receiveUserList);
        message.put("message",msg);
        message.put("wechat",null);
        long start = System.currentTimeMillis();
        executeHttp(message);
//        yhbcp_httpRequset(message);
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return JSON;
    }

    @RequestMapping("testDwr.do")
    public String testDwr() throws Exception{
        Map<String,Object> sendUser = new HashMap<>();
        sendUser.put("appId","portal_test");
        sendUser.put("userId","developer");
        sendUser.put("name","管理员");

        List<Map<String,Object>> receiveUserList = new ArrayList<>();
        Map<String,Object> receiveUser = new HashMap<>();
        receiveUser.put("appId","portal_test");
        receiveUser.put("userId","1");
        receiveUser.put("name","renxin");
        receiveUserList.add(receiveUser);

        Map<String,Object> msg = new HashMap<>();
        Map<String,Object> content = new HashMap<>();
        content.put("message","收到了吧11111111111111111111");
        content.put("id","你好");
        msg.put("title","消息测试");
        msg.put("content",JSONUtils.toJSONString(content));
        msg.put("text","你好");
        msg.put("selfType","4");
        msg.put("toAllUser",false);

        String type = "0";//系统内部推送
        String type1 = "1";//email
        String type2 = "5"; //IM
        String type3 = "4";//app
        String type4 = "2";//微信
        String type5 = "3";//短信
        List<String> types = new ArrayList<>();
        types.add(type);
        msg.put("messageTypes",types);
        Map<String,Object> message = new HashMap<>();
        message.put("user",sendUser);
        message.put("userlist",receiveUserList);
        message.put("message",msg);
        message.put("wechat",null);
        long start = System.currentTimeMillis();
        executeHttp(message);
//        yhbcp_httpRequset(message);
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"ms");
        return JSON;
    }


    public void executeHttp(Map<String,Object> message) throws IOException {
        Properties properties = new Properties();
        properties.load(TestSendMessageController.class.getClassLoader().getResourceAsStream("TaMessage.properties"));
        String ticket =  properties.getProperty("ticket");
        String msgCenterAddr = properties.getProperty("msgCenterAddr");
        if(msgCenterAddr.lastIndexOf("/") != -1) {
            msgCenterAddr = msgCenterAddr + "/";
        }
        String path = msgCenterAddr + "messageHttp/messageHttpController!sendMessage.do";
        HttpPost post = new HttpPost(path);
        String content = JSONObject.toJSONString(message);
        CloseableHttpClient client = HttpClients.createDefault();
        MultipartEntityBuilder reqEntitybuilder = MultipartEntityBuilder.create();
        reqEntitybuilder.addTextBody("ticket", ticket);
        reqEntitybuilder.addTextBody("msgjsonstr", content, ContentType.create("text/plain", Charset.forName("UTF-8")));

        HttpEntity entity = reqEntitybuilder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while((line = reader.readLine()) != null) {
            sb.append(line);
        }

        is.close();
        response.close();
        System.out.println(sb.toString());
    }


    public void yhbcp_httpRequset(Map<String,Object> message) throws Exception{
        Properties properties = new Properties();
        properties.load(TestSendMessageController.class.getClassLoader().getResourceAsStream("TaMessage.properties"));
        //
        String ticket =  properties.getProperty("ticket");
        //服务地址
        String msgCenterAddr = properties.getProperty("msgCenterAddr");
       /* //参数
        Map<String,Object> content = new HashMap<>();
        content.put("ticket",ticket);
        content.put("msgjsonstr", JSONUtils.toJSONString(message));
        //文件数组暂时设置
        content.put("files",null);*/
        //流水号
        String request_id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);
        //请求时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        //mock服务
        String mock = "";
        Map<String,Object> map = new HashMap<>();
        map.put("ticket",ticket);
        map.put("msgjsonstr",message);

        String biz_content = JSONUtils.toJSONString(map);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("biz_content", biz_content);
        paramMap.put("access_key", access_key);
        paramMap.put("version", version);
        paramMap.put("format", format);
        paramMap.put("request_id", request_id);
        paramMap.put("timestamp", timestamp);
        paramMap.put("mock", mock);

        String source = generateSignSource(paramMap);
        //签名串
        String sign = sign(source,"C:\\Users\\Administrator\\Desktop\\3.0.2-release\\RSA密钥生成工具\\consumer_private.keystore");
        //原生http调用签名串中的+需要转义为%2B (如果使用httpclient、okhttp等组件不需要)
        sign = sign.replaceAll("[+]", "%2B");

        //参数串
        String paramStr = source +"&sign=" + sign;

        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL url = new URL("http://mz.yhmdlife.com/yhbcp-engine/rest/SEND_TAMESSAGE");
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //post传参
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(paramStr);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charset.forName("UTF-8")));
            String line;
            StringBuilder resultBuilder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                resultBuilder.append(line);
            }
        //结果输出
            System.out.println(resultBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
            }
        }

    }
    public String generateSignSource(Map params) {
        Set<String> keySet = params.keySet();
        List<String> keys = new ArrayList<>();
        for (String key : keySet) {
            if (params.get(key) != null && StringUtils.isNotBlank(params.get(key).toString())) {
                keys.add(key);
            }
        }
        Collections.sort(keys);
        StringBuilder builder = new StringBuilder();
        for (int i = 0, size = keys.size(); i < size; i++) {
            String key = keys.get(i);
            Object value = params.get(key);
            builder.append(key);
            builder.append("=");
            builder.append(value);
//拼接时，不包括最后一个&字符
            if (i != size - 1) {
                builder.append("&");
            }
        }
        return builder.toString();
    }
    public String sign(String source, String keyFile) throws Exception {
//读取解析私钥（解析完成的PrivateKey对象建议缓存起来）
        InputStream in = new FileInputStream(keyFile);
        PrivateKey privateKey = null;
        String sign = null;
        try {
            byte[] keyBytes = IOUtils.toByteArray(in);
            byte[] encodedKey = Base64.getDecoder().decode(keyBytes);
            KeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(keySpec);
        } finally {
            IOUtils.closeQuietly(in);
        }
        if (privateKey != null) {
//签名
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(source.getBytes());
            byte[] signed = signature.sign();
//取base64，得到签名串
            sign = Base64.getEncoder().encodeToString(signed);
        }
        return sign;
    }
}
